package com.isky.visual.exception;

import com.isky.visual.result.CodeMsg;
import com.isky.visual.result.ResultVo;
import com.isky.visual.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.isky.visual.result.CodeMsg.DATA_FORMATTED_ERROR;
import static com.isky.visual.result.CodeMsg.SERVER_ERROR;

/**
 * @ClassName : GlobalExceptionHandler
 * @Description : 全局异常 所有的异常都会拦截 并且都会返回给前端
 * @Author :wudl
 * @Date: 2020-04-12 19:26
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

//    @ResponseBody
//    @ExceptionHandler(value = Exception.class)
//    public ResultVo<String> exceptionHandler(HttpServletRequest request, Exception e) {
//
//        log.error(e.getMessage());
//        if (e instanceof GlobalException) {
//            GlobalException ex = (GlobalException) e;
//            return ResultVo.error(ex.getCm());
//        } else if (e instanceof BindException) {
//            BindException ex = (BindException) e;
//            List<ObjectError> errorList = ex.getAllErrors();
//            ObjectError objectError = errorList.get(0);
//            String defaultMessage = objectError.getDefaultMessage();
//            return ResultVo.error(CodeMsg.BIND_ERROR.fillArgs(defaultMessage));
//        } else {
//            return ResultVo.error(CodeMsg.SERVER_ERROR);
//        }
//    }

    //指定出现什么异常执行这个方法
    @ExceptionHandler(Exception.class)
    @ResponseBody //为了返回数据
    public ResultVo<String> error(Exception e) {
        e.printStackTrace();

        if (e instanceof HttpMessageNotReadableException) {

            return ResultVo.error(CodeMsg.DATA_FORMATTED_ERROR);
        }
        return ResultVo.error(CodeMsg.SERVER_ERROR);
    }

    //特定异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody //为了返回数据
    public ResultVo<String> error(ArithmeticException e) {
        e.printStackTrace();
        return ResultVo.error(CodeMsg.BIND_ERROR);
    }

    //自定义异常
    @ExceptionHandler(GlobalException.class)
    @ResponseBody //为了返回数据
    public ResultVo<CodeMsg> error(GlobalException e) {
        log.error(e.getMessage());
        e.printStackTrace();

        return ResultVo.error(e.getCm());
    }
}
